package com.dilidili.utils;
import com.dilidili.controller.VideoController;
import com.util.TransferUtil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;

/**
 * @description: 获取视频帧，生成图片
 * @author zyb
 * @date 2020-07-12
 */
public class VideoUtil {
    public static final Logger log = LoggerFactory.getLogger(VideoUtil.class);

    /**
     * 获取视频第一帧
     * @param videoPath 视频地址
     * @param imgPath 生成图片的名字（包含全路径）
     * @throws Exception
     */
    public static void getVideoPicture(String videoPath,String imgPath) throws Exception{
        File imgFile = new File(imgPath);
        //判断保存的文件的文件夹是否存在，不存在创建。
        if (!imgFile.getParentFile().exists()) {
            log.info("保存文件的文件夹不存在，创建。");
            imgFile.getParentFile().mkdirs();
        }
        File videoFile = new File(videoPath);
        if (videoFile.exists()) {
            log.info("视频存在：{}",videoFile);
            //实例化“截取视频首帧”对象
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoFile);
            ff.start();
            int ftp = ff.getLengthInFrames();
            int flag=0;
            Frame frame = null;
            while (flag <= ftp) {
                //获取帧
                frame = ff.grabImage();
                //过滤前1帧，避免出现全黑图片
                if ((flag>1)&&(frame != null)) {
                    break;
                }
                flag++;
            }
            ImageIO.write(frameToBufferedImage(frame), "jpg", imgFile);
            ff.close();
            ff.stop();
        }else {
            log.info("视频不存在：{}",videoFile);
        }
    }

    /**
     * 帧转为流
     * @param frame
     * @return
     */
    private static RenderedImage frameToBufferedImage(Frame frame) {
        //创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        return bufferedImage;
    }


    public static void main(String[] args) throws Exception {
        Boolean transform = TransferUtil.transform("E:\\百度网盘传输\\ffmpeg-20200220-56df829-win64-static\\bin\\ffmpeg.exe",
                "F:\\1.mp4",
                "C:\\Users\\31444\\AppData\\Local\\Temp\\tomcat-docbase.9900.7233178598952830064\\business\\shops\\upload\\2022\\04\\04\\00\\057b63af-3f65-4f50-afc1-f604ea54b5a9_480x320.mp4", "480x320");
        System.out.println(transform);
    }

}